<template>
    <view>
        <!-- 评论弹窗 -->
        <u-popup :show="show && !noCommentList" :overlay="false" mode="bottom" @close="closeInputBox" :round="20" :closeable="true" zIndex="502">
            <view class="comment-popup">
                <!-- 弹窗头部 -->
                <view class="comment-header">
                    <view class="comment-title">共{{ commentTotal }}条评论</view>
                </view>
                
                <!-- 评论列表 -->
                <scroll-view class="comment-list" scroll-y @scrolltolower="onLoadMoreComments" @click="inputBoxShow = false">
                    <view class="comment-item" v-for="(comment, index) in commentList" :key="index">
                        <view class="comment-avatar">
                            <image :src="comment.userpic" mode="aspectFill"></image>
                        </view>
                        <view class="comment-content">
                            <view class="comment-user">
                                <text class="username">{{ comment.member.nickname }}</text>
                            </view>
                            <view class="comment-text">{{ comment.content }}</view>
                            <view class="comment-footer">
                                <text class="comment-time">{{ comment.create_time }}</text>
                                <text class="comment-reply-btn" @click.stop="onReplyToComment(comment)">回复</text>
                            </view>
                            
                                                         <!-- 二级回复 -->
                             <view v-if="comment.reply_count && comment.reply_count > 0 && comment.expanded" class="reply-list">
                                 <view class="reply-item" v-for="(reply, replyIndex) in comment.replies" :key="replyIndex">
                                     <view class="reply-avatar">
                                         <image :src="reply.userpic" mode="aspectFill"></image>
                                     </view>
                                     <view class="reply-content">
                                         <view class="reply-user">
                                             <text class="reply-username">{{ reply.current_member.nickname }}</text>
                                             <u-icon v-if="reply.reply_member" class="reply-icon" name="play-right-fill" size="18rpx" color="#999"></u-icon>
                                             <text v-if="reply.reply_member" class="reply-to-user">{{ reply.reply_member.nickname }}</text>
                                         </view>
                                         <view class="reply-text">{{ reply.content }}</view>
                                         <view class="reply-footer">
                                             <text class="reply-time">{{ reply.update_time }}</text>
                                            <text class="reply-reply-btn" @click.stop="onReplyToComment(reply)">回复</text>
                                         </view>
                                     </view>
                                 </view>
                            </view>
                            
                            <!-- 加载中 -->
                            <view v-if="comment.expanded && replyLoadingMap[comment.id]" class="reply-loading">
                                <u-loading-icon mode="spinner" size="28rpx" color="#999"></u-loading-icon>
                            </view>
                            
                            <!-- 展开收起按钮 -->
                            <view v-if="comment.reply_count > 0" class="expand-btn" @click="onToggleReplies(comment)">
                                    <text>{{ getExpandButtonText(comment) }}</text>
                                    <text class="expand-arrow">
                                         <u-icon :name="getExpandButtonText(comment) === '收起' ? 'arrow-up' : 'arrow-down'" size="18rpx" color="#666"></u-icon>
                                    </text>
                                </view>
                        </view>
                    </view>
                    
                    <view class="list-footer">
                        <text v-if="commentLoading">正在加载...</text>
                        <text v-else-if="!commentHasMore">已经加载全部</text>
                    </view>
                </scroll-view>
                
                <!-- 底部输入框 -->
                <view class="comment-input" @click.stop="onOpenCommentInput">
                    <u-textarea 
                        class="textarea" 
                        v-model="commentInputValue"
                        placeholder="Hi! 说点什么吧" 
                        height="68rpx" 
                        :auto-height="true"
                        readonly
                    ></u-textarea>
                </view>
            </view>
        </u-popup>

        <!-- 固定在底部的真实输入框（随键盘上移） -->
        <view class="input-box" :style="{ bottom: keyboardHeight + 'px' }" v-if="inputBoxShow">
            <view class="input-box-item">
                <u-textarea
                    class="textarea"
                    v-model="commentValue"
                    :placeholder="inputPlaceholder"
                    :focus="inputFocus"
                    confirmType="send"
                    @focus="onInputFocus"
                    @blur="onInputBlur"
                    @confirm="onHandleSend"
                    @keyboardheightchange="onKeyboardHeightChange"
                    @input="onTyping"
                    :cursorSpacing="16"
                    :adjustPosition="false"
                    :auto-height="true"
                    height="72rpx"
                />
                <view class="send-btn" @click.stop="onHandleSend">发送</view>
            </view>
        </view>

        <!-- 输入框遮罩 -->
        <view 
            class="input-box-mask" 
            :class="{ show: maskStatus}" 
            @click="closeInputBox">
        </view>
    </view>
</template>

<script>
export default {
    name: 'CommentPop',
    props: {
        show: {
            type: Boolean,
            default: false
        },
        postId: {
            type: [String, Number],
            default: ''
        },
        commentCount: {
            type: [String, Number],
            default: 0
        },
        noCommentList: {
            type: Boolean,
            default: false
        },
        // 评论数据
        commentList: {
            type: Array,
            default: () => []
        },
        commentTotal: {
            type: [String, Number],
            default: 0
        },
        commentHasMore: {
            type: Boolean,
            default: true
        },
        commentLoading: {
            type: Boolean,
            default: false
        },
        // 回复加载状态
        replyLoadingMap: {
            type: Object,
            default: () => ({})
        },
        // 键盘高度
        keyboardHeight: {
            type: Number,
            default: 0
        },
        // 帖子发布者名字
        postOwnerName: {
            type: String,
            default: ''
        }
    },
    data() {
        return {
            // 输入框相关
            commentValue: '',
            commentInputValue: '',
            inputFocus: false,
            inputBoxShow: false,
            maskStatus: false,
            
            // 回复相关
            replyParentId: 0,
            
            // 输入来源
            inputFrom: 'popup'
        }
    },
    watch: {
        show(newVal) {
            if (newVal) {
            this.maskStatus = true
                if (this.noCommentList) {
                    this.inputBoxShow = true
                    // 当noCommentList为true时，自动聚焦输入框
                    this.$nextTick(() => {
            this.inputFocus = true
                    })
                }
            }
        },
        noCommentList: {
            handler(newVal) {
                if (newVal && this.show) {
                    // 当noCommentList变为true时，显示输入框并聚焦
                    this.inputBoxShow = true
                    this.$nextTick(() => {
            this.inputFocus = true
                    })
                }
            },
            immediate: true
        }
    },
    computed: {
        inputPlaceholder() {
            if (this.replyParentId) {
                const name = this.findCommentNicknameById(this.replyParentId) || ''
                return name ? ('回复 ' + name + '：') : '请输入评论'
            }
            // 不是回复时，显示贴主的名字
            const postOwnerName = this.findPostOwnerName()
            return postOwnerName ? ('回复 ' + postOwnerName + '：') : '请输入评论'
        }
    },
    methods: {
        // 事件处理 - 通知父组件
        onLoadMoreComments() {
            this.$emit('load-more-comments')
        },

        onReplyToComment(comment) {
            this.inputFrom = 'popup'
            this.replyParentId = comment.id || 0
            
            this.commentValue = ''
            this.commentInputValue = ''
            this.inputFocus = true
            this.inputBoxShow = true
            this.maskStatus = true
            
            // 通知父组件处理回复
            this.$emit('reply-to-comment', comment)
        },

        onOpenCommentInput() {
            this.inputFrom = 'popup'
            this.replyParentId = 0
            this.commentValue = ''
            this.commentInputValue = ''
            this.inputFocus = true
            this.inputBoxShow = true
            this.maskStatus = true
        },

        onToggleReplies(comment) {
            // 通知父组件处理展开/收起
            this.$emit('toggle-replies', comment)
        },

        onHandleSend() {
            const content = this.commentValue.trim()
            if (!content) {
                uni.showToast({ title: '请输入内容', icon: 'none' })
                return
            }
            
            // 通知父组件处理发送
            this.$emit('send-comment', {
                content: content,
                parentId: this.replyParentId
            })
            
            // 清空输入
            this.commentValue = ''
            this.commentInputValue = ''
            this.replyParentId = 0
            
            // 只有在直接评论模式（noCommentList为true）时才关闭输入框
            // 有评论区时保持评论区打开，只关闭输入框
            if (this.noCommentList) {
                this.closeInputBox()
                    } else {
                // 有评论区时，只关闭输入框，保持评论区打开和背景遮罩
                this.inputBoxShow = false
                this.inputFocus = false
                // 不关闭背景遮罩，保持评论区弹窗打开
            }
        },

        // 关闭输入框
        closeInputBox() {
            this.inputBoxShow = false
            this.maskStatus = false
            this.inputFocus = false
            // 重置回复状态，避免影响下次直接回复贴主
            this.replyParentId = 0
            this.$emit('close')
        },

        // 输入框聚焦
        onInputFocus() {
            this.inputFocus = true
        },

        // 输入框失焦
        onInputBlur() {
            setTimeout(() => { 
                this.inputFocus = false 
            }, 50)
        },

        // 键盘高度变化
        onKeyboardHeightChange(e) {
            const height = e?.height || 0
            this.$emit('keyboard-height-change', height)
        },

        // 输入内容变化
        onTyping(e) {
            const val = e?.detail?.value !== undefined ? e.detail.value : this.commentValue
            this.commentValue = val
            if (this.inputFrom === 'popup') {
                this.commentInputValue = val
            }
        },

        // 获取展开按钮文本
        getExpandButtonText(comment) {
            if (!comment.expanded) {
                return '展开'
            }
            
            if (this.replyLoadingMap[comment.id]) {
                return '加载中...'
            }
            
            const hasMoreData = comment.replies && comment.replies.length < comment.reply_count
            
            return hasMoreData ? '展开更多' : '收起'
        },

        // 根据ID查找评论昵称
        findCommentNicknameById(id) {
            if (!id) return ''
            
            const comment = this.commentList.find(c => c && c.id === id)
            if (comment && comment.member) return comment.member.nickname || ''
            
            for (const commentItem of this.commentList) {
                if (commentItem.replies && commentItem.replies.length > 0) {
                    const hit = commentItem.replies.find(r => r && r.id === id)
                if (hit && hit.current_member) return hit.current_member.nickname || ''
                }
            }
            return ''
        },

        // 查找贴主的名字
        findPostOwnerName() {
            // 从父组件传递的帖子数据中获取发布者名字
            // 这里需要父组件传递帖子发布者信息
            return this.postOwnerName || '贴主'
        }
    }
}
</script>

<style lang="scss" scoped>
    .comment-popup {
        height: 60vh;
        background: #fff;
        border-radius: 20rpx 20rpx 0 0;
        overflow: hidden;
        display: flex;
        flex-direction: column;
    }

    .comment-header {
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 24rpx 32rpx;
        border-bottom: 1rpx solid #f0f0f0;
    }

    .comment-title {
        font-size: 32rpx;
        font-weight: 500;
        color: #333;
    }

    .comment-list {
        flex: 1;
        padding: 0 32rpx;
        height: 300rpx;
        box-sizing: border-box;
    }

    .comment-item {
        display: flex;
        padding: 24rpx 0;
        border-bottom: 1rpx solid #f8f8f8;
    }

    .comment-avatar {
        margin-right: 16rpx;
    }

    .comment-avatar image {
        width: 60rpx;
        height: 60rpx;
        border-radius: 50%;
    }

    .comment-content {
        flex: 1;
    }

    .comment-user {
        margin-bottom: 8rpx;
    }

    .username {
        font-size: 28rpx;
        font-weight: 500;
        color: #999;
    }

    .comment-text {
        font-size: 28rpx;
        color: #333;
        line-height: 1.5;
        margin-bottom: 8rpx;
    }

    .comment-footer {
        display: flex;
        align-items: center;
        margin-top: 8rpx;
    }

    .comment-time {
        font-size: 24rpx;
        color: #999;
    }

    .comment-reply-btn {
        font-size: 24rpx;
        color: #0DA3FF;
        padding: 4rpx 8rpx;
    }

    .reply-list {
        margin-top: 16rpx;
    }

    .reply-item {
        display: flex;
        margin-bottom: 16rpx;
    }

    .reply-avatar {
        margin-right: 12rpx;
        flex-shrink: 0;
    }

    .reply-avatar image {
        width: 48rpx;
        height: 48rpx;
        border-radius: 50%;
    }

    .reply-content {
        flex: 1;
    }

    .reply-user {
        margin-bottom: 6rpx;
        display: flex;
        align-items: center;
    }

    .reply-username {
        font-size: 24rpx;
        color: #999999;
        font-weight: 500;
    }

    .reply-icon {
        margin: 5rpx 5rpx 0;
    }

    .reply-to-user {
        font-size: 24rpx;
        color: #999999;
    }

    .reply-text {
        font-size: 26rpx;
        color: #333;
        line-height: 1.5;
        margin-bottom: 6rpx;
    }

    .reply-footer {
        display: flex;
        align-items: center;
    }

    .reply-time {
        font-size: 22rpx;
        color: #999;
    }

    .reply-reply-btn {
        font-size: 22rpx;
        color: #0DA3FF;
        padding: 2rpx 6rpx;
    }

    .reply-loading {
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 16rpx 0;
        color: #999;
        font-size: 24rpx;
        margin-left: 50rpx;
        
        &::after {
            position: absolute;
            content: "";
            width: 40rpx;
            height: 1rpx;
            background: #DDDDDD;
            top: 50%;
            transform: translateY(-50%);
            left: -50rpx;
        }
    }

    .expand-btn {
        position: relative;
        display: flex;
        align-items: center;
        padding: 12rpx 0;
        color: #666;
        font-size: 24rpx;
        margin-left: 50rpx;

        &::after {
            position: absolute;
            content: "";
            width: 40rpx;
            height: 1rpx;
            background: #DDDDDD;
            top: 50%;
            transform: translateY(-50%);
            left: -50rpx;
        }
    }

    .expand-arrow {
        margin-left: 4rpx;
        font-size: 20rpx;
    }

    .comment-input {
        padding: 16rpx 32rpx 32rpx;
        border-top: 1rpx solid #f0f0f0;
    }

.textarea {
    padding: 12rpx 24rpx;
        box-sizing: border-box;
    background: #F6F6F6;
    border-radius: 16rpx;
    font-size: 28rpx;
    line-height: 1.4;
}

.list-footer {
    padding: 20rpx 0 40rpx;
    text-align: center;
    color: #999;
    font-size: 24rpx;
}

.input-box-mask {
    position: fixed;
    z-index: -1;
    inset: 0;
    opacity: 0;
    background: rgba(0,0,0,0.5);
    transition: all 0.3s ease-in-out;
}

.input-box-mask.show {
    display: block;
    z-index: 501;
    opacity: 1;
}

.input-box {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    padding: 28rpx 24rpx 28rpx;
    background: rgba(255,255,255,0.96);
    box-shadow: 0 -8rpx 20rpx rgba(0,0,0,0.04);
    z-index: 504;
    }

    .input-box-item {
        border-radius: 50rpx;
        display: flex;
        align-items: center;
    }

    .send-btn {
        margin-left: 16rpx;
        padding: 0 28rpx;
        height: 56rpx;
        line-height: 56rpx;
        border-radius: 40rpx;
        color: #333;
        font-size: 32rpx;
        flex-shrink: 0;
}
</style>
